package cn.dao.Impl;

import cn.base.Impl.IBaseDaoImpl;
import cn.dao.ForumDao;
import cn.domain.Forum;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Queue;

/**
 * Created by Administrator on 2017/4/1 0001.
 */
@Repository
@SuppressWarnings("unchecked")
public class ForumDaoImpl extends IBaseDaoImpl<Forum> implements ForumDao {
    /**
     * 重写父类的查询所有方法，根据position_排序
     * @return
     */
    @Override
    public List<Forum> findAll() {
        String hql = "from Forum Order By position";
        return session().createQuery(hql).list();
    }

    /**
     * 重写父类的保存方法，加入保存板块时，设置position的为id的值
     * @param entity
     */
    public void save(Forum entity) {
        super.save(entity);
        entity.setPosition(entity.getId().intValue());
    }

    @Override
    public void moveUp(Long id) {
        Forum forum = getById(id);
        int f1=forum.getPosition();
        String hql="From Forum f where f.position<? Order By f.position Desc";
        Query query=session().createQuery(hql);
        query.setParameter(0,f1);
        query.setFirstResult(0);
        query.setMaxResults(1);
        Forum forum1= (Forum) query.uniqueResult();
        if(forum1!=null){
            forum.setPosition(forum1.getPosition());
            forum1.setPosition(f1);
            update(forum);
            update(forum1);
        }
    }
    public void moveDown(Long id) {
        Forum forum = getById(id);
        int f1=forum.getPosition();
        String hql="From Forum f where f.position>? Order By f.position";
        Query query=session().createQuery(hql);
        query.setParameter(0,f1);
        query.setFirstResult(0);
        query.setMaxResults(1);
        Forum forum1= (Forum) query.uniqueResult();
        if(forum1!=null){
            forum.setPosition(forum1.getPosition());
            forum1.setPosition(f1);
            update(forum);
            update(forum1);
        }
    }

    @Override
    public void moveTop(Long id) {
        Forum forum = getById(id);
        int f1=forum.getPosition();
        String hql="From Forum f where f.position<? Order By f.position";
        Query query=session().createQuery(hql);
        query.setParameter(0,f1);
        query.setFirstResult(0);
        query.setMaxResults(1);
        Forum forum1= (Forum) query.uniqueResult();
        if(forum1!=null){
            forum.setPosition(forum1.getPosition());
            forum1.setPosition(f1);
            update(forum);
            update(forum1);
        }
    }
}
